package com.four.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.four.shop.dao.CategoryDao;
import com.four.shop.entity.Category;
import com.four.shop.service.CategoryService;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
 * @Author:wsy
 * @Date: 2021/12/9/15:35
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public List<Category> tree() {
        //从Redis中查询是否存在
        String category = redisTemplate.opsForValue().get("four:shop:category:");
        if(category!=null && StringUtils.isNotEmpty(category)){
            List<Category> categoryList= JSON.parseObject(category,new TypeReference<List<Category>>(){});
            return categoryList;
        }else{
            RLock lock = redissonClient.getLock("four:shop:category:redission:one");
            lock.lock();
            try{
                //查询出所有的分类信息
                List<Category> treeList=categoryDao.selectAll();
                //2.筛选1级分类
                List<Category> treeListOne=treeList.stream().filter(item ->{
                    return item.getParentid().equals(0);
                }).map(item ->{
                    //每一个item就是一个分类
                    //设置二级分类
                    //获取二级分类
                    item.setChildren(getChildren(item.getCatId(),treeList));
                    return item;
                }).collect(Collectors.toList());
                String s = JSON.toJSONString(treeListOne);
                redisTemplate.opsForValue().set("four:shop:category:",s,1, TimeUnit.MINUTES);
                return treeListOne;
            }finally {
                //释放锁
                lock.unlock();
            }
        }

    }

    private List<Category> getChildren(Integer catId, List<Category> treeList) {
        List<Category> child=treeList.stream().filter(item ->{
            return item.getParentid().equals(catId);
        }).map(item ->{
            //item就是二级分类
            item.setChildren(getChildren(item.getCatId(),treeList));
            return item;
        }).collect(Collectors.toList());
        return child;
    }

    /**
     * 添加分类
     * @param category
     * @return
     */
    @Override
    public R addTree(Category category) {
        category.setParentid(0);
        categoryDao.addTree(category);
        return R.ok();
    }

    /**
     * 添加商品分类的子目录
     * @param id
     * @param category
     */
    @Override
    public void addTreeSon(Integer id, Category category) {
        category.setParentid(id);
        categoryDao.addTree(category);
    }


    /**
     * 根据获取的id删除
     * 1.根据id查询此数据目录下有无数据，
     * 2.有的话全部删除，没有删除此数据
     * @param id
     */
    @Override
    public int delTree(Integer id) {
        int i=0;
        //根据id查询看看有无下一级
        List<Category> categoryList=categoryDao.getCatgory(id);
        if(categoryList!=null && categoryList.size()>0){
            for (Category type : categoryList) {
                i=i+delTree(type.getCatId());
            }
        }
        i+=id;
        categoryDao.delTreeById(id);
        return i;
    }

    @Override
    public R nextLevel(Integer id) {
        List<Category> categoryList=categoryDao.getCatgory(id);
        return R.ok().put("cat",categoryList);
    }

    /**
     * 三级树分页
     * @param map
     * @return
     */
    @Override
    public PageUtils treeList(Map<String, String> map) {
        //page  当前页
        Integer page = Integer.valueOf((String) map.get("page")==null?"1":(String) map.get("page"));
        //limit  每页多少条
        Integer limit = Integer.valueOf((String) map.get("limit")==null?"3":(String) map.get("limit"));
        //第几页第几条开始
        int size = (page-1)*limit;
        //查询出所有的分类信息
        List<Category> treeList=categoryDao.selectShowByPid();
        //查询第一级树
        List<Category> list = categoryDao.getPageList(size, limit);
        if (list.size()>0) {
            //查询第二级树
            for (Category category : list) {
                List<Category> listTow = categoryDao.getCatgory(category.getCatId());
                if (listTow.size()>0) {
                    //查询第三级树
                    for (Category cate : listTow) {
                        List<Category> listThrow = categoryDao.getCatgory(category.getCatId());
                        cate.setChildren(listThrow);
                    }
                }
                category.setChildren(listTow);
            }
        }
        //获取分页对象
        PageUtils pageUtils = new PageUtils(list, treeList.size(), limit, page);

        return pageUtils;
    }
}
